export type EventType = string | symbol

export type Handler<T = unknown> = (event: T) => void

export type EventHandlerList<T = unknown> = Array<Handler<T>>

export type WildcardHandler<T = Record<string, unknown>> = (type: keyof T, event: T[keyof T]) => void

export type WildCardEventHandlerList<T = Record<string, unknown>> = Array<WildcardHandler<T>>

export type EventHandlerMap<Events extends Record<EventType, unknown>> = Map<keyof Events | '*', EventHandlerList<Events[keyof Events]> | WildCardEventHandlerList<Events>>

export interface Emitter<Events extends Record<EventType, unknown>> {
  all: EventHandlerMap<Events>;
  on<Key extends keyof Events>(type: Key, handler: Handler<Events[Key]>): void;
  on(type: '*', handler: WildcardHandler<Events>): void
  once<Key extends keyof Events>(type: Key, handler: Handler<Events[Key]>): void;
  once(type: '*', handler: WildcardHandler<Events>): void
  off<Key extends keyof Events>(type: Key, handler?: Handler<Events[Key]>): void
  off(type: '*', handler: WildcardHandler<Events>): void
  emit<Key extends keyof Events>(type: Key, event: Events[Key]): void
}

export function mitt<Events extends Record<EventType, unknown>>(
  all?: EventHandlerMap<Events>,
): Emitter<Events> {
  type GenericEventHandler = Handler<Events[keyof Events]> | WildcardHandler<Events>
  all = all || new Map()
  return {
    /**
     * @description A Map of event names to registered handler functions.
     */
    all,

    /**
     * @description Register an event handler for the given type.
     * @param {string|symbol} type Type of event to listen for, or `'*'` for all events
     * @param {Function} handler Function to call in response to given event
     * @memberOf mitt
     */
    on<Key extends keyof Events>(type: Key, handler: GenericEventHandler) {
      const handlers: Array<GenericEventHandler> | undefined = all.get(type)
      if (handlers) {
        handlers.push(handler)
      } else {
        all.set(type, [handler] as EventHandlerList<Events[keyof Events]>)
      }
    },

    /**
     * @description Register an event handler only once for the given type.
     * @param {string|symbol} type Type of event to listen for, or `'*'` for all events
     * @param {Function} handler Function to call in response to given event
     * @memberOf mitt
     */
    once<Key extends keyof Events>(type: Key, handler: GenericEventHandler) {
      if (type === '*') {
        const onceHandler: WildcardHandler<Events> = (t, e) => {
          this.off(type, onceHandler);
          (handler as WildcardHandler<Events>)(t, e)
        };
        (onceHandler as any).mitt_original = handler
        this.on(type, onceHandler)
      } else {
        const onceHandler: Handler<Events[Key]> = (e) => {
          this.off(type, onceHandler);
          (handler as Handler<Events[Key]>)(e)
        };
        (onceHandler as any).mitt_original = handler
        this.on(type, onceHandler)
      }
    },

    /**
     * @description Remove an event handler for the given type.If `handler` is omitted, all handlers of the given type are removed.
     * @param {string|symbol} type Type of event to unregister `handler` from (`'*'` to remove a wildcard handler)
     * @param {Function} [handler] Handler function to remove
     * @memberOf mitt
     */
    off<Key extends keyof Events>(type: Key, handler?: GenericEventHandler) {
      const handlers: Array<GenericEventHandler> | undefined = all.get(type)
      if (handlers) {
        if (handler) {
          for (let i = 0; i < handlers.length; i++) {
            const registeredHandler = handlers[i]
            if (registeredHandler === handler || (registeredHandler as any).mitt_original === handler) {
              handlers.splice(i, 1)
              break
            }
          }
        } else {
          all.set(type, [])
        }
      }
    },

    /**
     * @description Invoke all handlers for the given type.
     * @description If present, `'*'` handlers are invoked after type-matched handlers.
     * @param {string|symbol} type The event type to invoke
     * @param {Any} [evt] Any value (object is recommended and powerful), passed to each handler
     * @memberOf mitt
     */
    emit<Key extends keyof Events>(type: Key, evt?: Events[Key]) {
      let handlers = all.get(type)
      if (handlers) {
        (handlers as EventHandlerList<Events[keyof Events]>)
          .slice()
          .forEach((handler) => {
            handler(evt!)
          })
      }
      handlers = all.get('*')
      if (handlers) {
        (handlers as WildCardEventHandlerList<Events>)
          .slice()
          .forEach((handler) => {
            handler(type, evt!)
          })
      }
    },
  }
}
